package ch.abcm.remsmobile.REMSMobile.network;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
import ch.abcm.remsmobile.REMSMobile.R;
import ch.abcm.remsmobile.REMSMobile.externnotifier.ExternNotifierController;
import ch.abcm.remsmobile.REMSMobile.network.networkutils.SSIDScanner;
import ch.abcm.remsmobile.REMSMobile.preferences.PrefsActivity;

public class NetworkController extends BroadcastReceiver {

	public static final String NOT_CONNECTED = "Netzwerk ausgefallen";
	public static final String CONNECTED = "Netzwerkverbindung wieder hergestellt";

	public static final String TAG = "NetworkController";

	public static final String REMS_SSID = "REMS_PI_Network";
	public static final String REMS_WIFI_PASSWORD = "qwertzuiop";
	public static final String UPDATE_STATUS_ACTION = "ch.bfh.abcm.rems.NetworkController.UPDATE_STATUS";
	public static final long UPDATE_STATUS_WAITTIME = 1000 * 10; // 10 Sekunden

	@Override
	public void onReceive(final Context context, Intent intent) {
		Log.d(TAG, "IntentAction: " + intent.getAction());

		Intent networkIntent = null;
		SSIDScanner scanner = new SSIDScanner(context);
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
		String ssid = prefs.getString(PrefsActivity.KEY_PREFRENCES_NETWORK, REMS_SSID);
		Log.d(TAG, "SSID from preferences: "+ssid);
		if (!scanner.isDeviceConnectedToSSID(ssid)) {
			Log.i(TAG, "Device is not conneted to "+ ssid);
			networkIntent = ExternNotifierController.getSimpleMessageIntent(context.getResources().getString(
					R.string.network_disconnected));
		} else {
			Log.i(TAG, "Device is nconneted to "+ ssid);
			networkIntent = ExternNotifierController.getSimpleMessageIntent(context.getResources().getString(
					R.string.network_connected));
		}

		if (networkIntent != null) {
			Log.d(TAG, "Send Network Intent");
			context.sendBroadcast(networkIntent);
		}else {
			Log.e(TAG, "NetworkIntent was NULL");
		}

	}

}
